import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:orginone/components/CommandWidget/index.dart';
import 'package:orginone/dart/core/chat/message.dart';
import 'package:orginone/dart/core/chat/session.dart';
import 'package:orginone/dart/core/public/enums.dart';
import 'package:orginone/utils/date_util.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

import '../../../../dart/core/target/base/target.dart';
import '../../../../routers/pages.dart';
import '../../../EmptyWidget/EmptyChat.dart';
import '../../../XLazy/XLazy.dart';
import 'components/DetailItemWidget/DetailItemWidget.dart';

class MessageListWidget extends StatefulWidget {
  final ISession? chat;
  const MessageListWidget({Key? key, this.chat}) : super(key: key);

  @override
  State<MessageListWidget> createState() => _MessageListState();
}

class _MessageListState extends State<MessageListWidget> {
  // MessageChatController get controller => Get.find();

  // ISession? get chat => widget.chat ?? controller.state.chat;
  final ScrollController _scrollController = ScrollController();
  bool isBuilded = false;

  ISession? chat;
  late String noReadCount = '';

  late GlobalKey scrollKey;

  final ItemScrollController itemScrollController = ItemScrollController();

  @override
  void dispose() {
    super.dispose();
    chat?.unMessage();
  }

  @override
  void initState() {
    super.initState();
    dynamic param = RoutePages.getPageParams;
    if (param is ISession) {
      chat = param;
    } else {
      param = RoutePages.getParentRouteParam();
      if (param is ISession) {
        chat = param;
      } else if (param is ITarget) {
        chat = param.session;
      } else {
        print('>>>>>>>>>> $param');
      }
    }
    scrollKey = GlobalKey();
    // MessageChatController chatCtrl;
    // if (!Get.isRegistered<MessageChatController>()) {
    //   chatCtrl = MessageChatController();
    //   chatCtrl.context = context;
    //   Get.put(chatCtrl);
    // } else {
    //   chatCtrl = Get.find<MessageChatController>();
    //   chatCtrl.context = context;
    // }
    if (!Get.isRegistered<PlayController>()) {
      PlayController playCtrl = PlayController();
      Get.lazyPut(() => playCtrl);
    }
    // chat?.onMessage((messages) => null).then((value) {
    //   if (!isBuilded) {
    //     if (mounted) {
    //       setState(() {});
    //     }
    //   }
    // });
  }

  @override
  Widget build(BuildContext context) {
    isBuilded = true;
    return null != chat
        ? !chat!.isLoaded
            ? FutureBuilder(
                future: chat!.onMessage((messages) => null),
                builder: (context, sho) {
                  if (sho.connectionState == ConnectionState.done) {
                    return _buildList(context);
                  }
                  return const Center(
                    child: CircularProgressIndicator(),
                  );
                })
            : _buildList(context)
        : Container();
  }

  Widget _buildList(BuildContext context) {
    if (chat!.isLoaded) {
      chat!.onMessage((messages) => null);
    }
    Future.delayed(const Duration(seconds: 0), () async {
      // 索引最新的位置
      _scrollToLatestIndex();
    });
    return CommandWidget<ISession>(
      type: 'session-${chat?.chatdata.fullId}',
      cmd: "new",
      builder: (context, args) {
        return XLazy<IMessage>(
          initDatas: chat?.messages ?? [],
          onInitLoad:  () async {
            return chat!.messages;
          },
          onLoad: () async {
            await chat!.moreMessage();
            return chat!.messages;
          },
          scrollController: _scrollController,
          builder: (context, datas) {
            return (chat!.messages.isEmpty)
                ? const EmptyChat()
                : Container(
                    padding: EdgeInsets.only(left: 10.w, right: 10.w),
                    color: Colors.white,
                    child: ListView.builder(
                      controller: _scrollController,
                      itemCount: chat!.messages.length,
                      reverse: true,
                      // shrinkWrap: true,
                      itemBuilder: (context, index) {
                        return _item(index);
                      },
                    ),
                  );
          },
        );
      },
    );
  }

  void _scrollToLatestIndex() {
    if (chat!.messages.isNotEmpty && _scrollController.hasClients) {
      // 滚动到最新的索引，比如最后一个
      _scrollController.jumpTo(0.0);
    }
  }

  Widget _item(int index) {
    ///兼容异常问题
    //     RangeError (index): Invalid value: Valid value range is empty: 0
    // #0 List.[] (dart:core-patch/growable_array.dart:264)
    // #1 RxList.[] (package:get/get_rx/src/rx_types/rx_iterables/rx_list.dart:60)
    // #2 _MessageListState._item (package:orginone/pages/chat/widgets/message_list.dart:84)
    // #3 _MessageListState.build.. (package:orginone/pages/chat/widgets/message_list.dart:76)
    // #4 _PositionedListState._buildItem (package:scrollable_positioned_list/src/positioned_list.dart:252)
    // #5 _PositionedListState.build. (package:scrollable_positioned_list/src/positioned_list.dart:206)
    if (chat!.messages.length <= index || chat!.messages.isEmpty) {
      return Container();
    }
    IMessage msg = chat!.messages[index];
    bool isHideMsg = false;
    for (var element in msg.labels) {
      if (element.label == "隐藏" && !msg.isMySend) {
        isHideMsg = true;
        break;
      }
    }
    if (isHideMsg) return Container();
    if (msg.isMySend &&
        msg.msgType == MessageType.notify.label &&
        msg.msgBody == '消息已发出，但被对方拒收了。') {
      return Container(
        alignment: Alignment.center,
        margin: const EdgeInsets.symmetric(vertical: 12),
        child: Text.rich(TextSpan(children: [
          TextSpan(text: "您已拉黑对方，消息已拒收", style: XFonts.size18Black9)
        ])),
      );
    }
    Widget currentWidget = DetailItemWidget(
      msg: msg,
      chat: chat!,
      key: ObjectKey(msg.metadata),
    );
    var time = _time(msg.createTime);
    var item = Column(children: [currentWidget]);
    if (index == 0) {
      item.children.add(Container(margin: EdgeInsets.only(bottom: 5.h)));
    }
    if (index == chat!.messages.length - 1) {
      item.children.insert(0, time);
      return item;
    } else {
      IMessage pre = chat!.messages[index + 1];
      var curCreateTime = DateTime.parse(msg.createTime);
      var preCreateTime = DateTime.parse(pre.createTime);
      var difference = curCreateTime.difference(preCreateTime);
      if (difference.inSeconds > 60 * 3) {
        item.children.insert(0, time);
        return item;
      }
      return item;
    }
  }

  Widget _time(String dateTime) {
    var content = CustomDateUtil.getDetailTime(DateTime.parse(dateTime));
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: 10.h, bottom: 10.h),
      child: Text(content, style: XFonts.size16Black9),
    );
  }
}
